<template>
  <div class="score-manage">
    <!-- 导航栏 -->
    <div class="nav">
      <button @click="activeTab = 'input'" :class="{ active: activeTab === 'input' }">成绩录入</button>
      <button @click="activeTab = 'analysis'" :class="{ active: activeTab === 'analysis' }">统计分析</button>
      <button @click="activeTab = 'warning'" :class="{ active: activeTab === 'warning' }">学情预警</button>
    </div>

    <!-- 成绩录入面板 -->
    <div v-if="activeTab === 'input'" class="panel">
      <div class="input-tabs">
        <button @click="inputType = 'single'" :class="{ active: inputType === 'single' }">单条录入</button>
        <button @click="inputType = 'batch'" :class="{ active: inputType === 'batch' }">Excel批量导入</button>
      </div>

      <!-- 单条录入 -->
      <div v-if="inputType === 'single'" class="single-input">
        <el-form :model="singleScore" inline @submit.prevent="addSingleScore">
          <el-form-item label="学生姓名">
            <el-input v-model="singleScore.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="科目">
            <el-select v-model="singleScore.subject" placeholder="请选择科目">
              <el-option label="数学" value="math" />
              <el-option label="语文" value="chinese" />
              <el-option label="英语" value="english" />
            </el-select>
          </el-form-item>
          <el-form-item label="分数">
            <el-input v-model.number="singleScore.score" type="number" placeholder="请输入分数" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addSingleScore">提交</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量导入 -->
      <div v-if="inputType === 'batch'" class="batch-input">
        <el-upload
          action="#"
          :auto-upload="false"
          :on-change="handleExcelUpload"
          accept=".xlsx,.xls"
        >
          <el-button type="primary">选择Excel文件</el-button>
        </el-upload>
        <el-button type="success" @click="importBatchScore" v-if="excelFile">导入数据</el-button>
      </div>

      <!-- 已录入列表 -->
      <el-table :data="scoreList" border style="margin-top: 20px;">
        <el-table-column prop="name" label="学生姓名" />
        <el-table-column prop="subject" label="科目" />
        <el-table-column prop="score" label="分数" />
      </el-table>
    </div>

    <!-- 统计分析面板 -->
    <div v-if="activeTab === 'analysis'" class="panel">
      <div class="stats">
        <el-card v-for="(stat, key) in statsData" :key="key" class="stat-card">
          <div class="stat-title">{{ stat.label }}</div>
          <div class="stat-value">{{ stat.value }}</div>
        </el-card>
      </div>

      <!-- 可视化图表 -->
      <div class="charts">
        <div class="chart-item">
          <h3>分数段分布</h3>
          <div id="scoreRangeChart" style="height: 300px;"></div>
        </div>
        <div class="chart-item">
          <h3>科目分数趋势</h3>
          <div id="subjectTrendChart" style="height: 300px;"></div>
        </div>
      </div>
    </div>

    <!-- 学情预警面板 -->
    <div v-if="activeTab === 'warning'" class="panel">
      <el-table :data="warningList" border>
        <el-table-column prop="name" label="学生姓名" />
        <el-table-column prop="subject" label="预警科目" />
        <el-table-column prop="reason" label="预警原因" />
        <el-table-column prop="level" label="预警等级">
          <template #default="scope">
            <el-tag :type="scope.row.level === '高危' ? 'danger' : 'warning'">
              {{ scope.row.level }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import * as echarts from 'echarts';
// 模拟Excel解析（实际项目需引入xlsx库）
import * as XLSX from 'xlsx';

// 状态管理
const activeTab = ref('input');
const inputType = ref('single');
const singleScore = ref({ name: '', subject: '', score: 0 });
const scoreList = ref([
  { name: '张三', subject: 'math', score: 85 },
  { name: '李四', subject: 'chinese', score: 78 },
  { name: '王五', subject: 'english', score: 92 }
]);
const excelFile = ref(null);
const statsData = ref({
  average: { label: '平均分', value: 0 },
  max: { label: '最高分', value: 0 },
  min: { label: '最低分', value: 0 },
  stdDev: { label: '标准差', value: 0 }
});
const warningList = ref([]);

// 单条录入提交
const addSingleScore = () => {
  if (singleScore.value.name && singleScore.value.subject && singleScore.value.score) {
    scoreList.value.push({ ...singleScore.value });
    singleScore.value = { name: '', subject: '', score: 0 };
    calculateStats();
    checkWarning();
  }
};

// Excel批量导入
const handleExcelUpload = (file) => {
  excelFile.value = file.raw;
};
const importBatchScore = () => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(sheet);
    // 假设Excel列是name、subject、score
    scoreList.value = [...scoreList.value, ...jsonData];
    calculateStats();
    checkWarning();
  };
  reader.readAsArrayBuffer(excelFile.value);
};

// 统计计算
const calculateStats = () => {
  const scores = scoreList.value.map(item => item.score);
  if (scores.length === 0) return;

  // 平均分
  const average = scores.reduce((sum, s) => sum + s, 0) / scores.length;
  // 最高/最低分
  const max = Math.max(...scores);
  const min = Math.min(...scores);
  // 标准差
  const variance = scores.reduce((sum, s) => sum + Math.pow(s - average, 2), 0) / scores.length;
  const stdDev = Math.sqrt(variance);

  statsData.value = {
    average: { label: '平均分', value: average.toFixed(1) },
    max: { label: '最高分', value: max },
    min: { label: '最低分', value: min },
    stdDev: { label: '标准差', value: stdDev.toFixed(2) }
  };
};

// 学情预警检测
const checkWarning = () => {
  warningList.value = scoreList.value
    .filter(item => item.score < 60)
    .map(item => ({
      name: item.name,
      subject: item.subject,
      reason: '分数低于及格线',
      level: item.score < 50 ? '高危' : '预警'
    }));
};

// 图表初始化
const initCharts = () => {
  // 分数段分布
  const rangeChart = echarts.init(document.getElementById('scoreRangeChart'));
  const ranges = [
    { name: '0-60', count: scoreList.value.filter(s => s.score < 60).length },
    { name: '60-80', count: scoreList.value.filter(s => s.score >= 60 && s.score < 80).length },
    { name: '80-100', count: scoreList.value.filter(s => s.score >= 80).length }
  ];
  rangeChart.setOption({
    xAxis: { type: 'category', data: ranges.map(r => r.name) },
    yAxis: { type: 'value' },
    series: [{ type: 'bar', data: ranges.map(r => r.count) }]
  });

  // 科目分数趋势
  const trendChart = echarts.init(document.getElementById('subjectTrendChart'));
  const subjects = ['math', 'chinese', 'english'];
  const subjectScores = subjects.map(sub => {
    const subScores = scoreList.value.filter(s => s.subject === sub).map(s => s.score);
    return subScores.length > 0 ? subScores.reduce((a, b) => a + b) / subScores.length : 0;
  });
  trendChart.setOption({
    xAxis: { type: 'category', data: subjects },
    yAxis: { type: 'value' },
    series: [{ type: 'line', data: subjectScores }]
  });
};

// 监听数据变化，更新统计和图表
watch(scoreList, () => {
  calculateStats();
  checkWarning();
  if (activeTab.value === 'analysis') {
    initCharts();
  }
}, { deep: true });

// 页面加载时初始化
onMounted(() => {
  calculateStats();
  checkWarning();
});
</script>

<style scoped>
.score-manage {
  padding: 20px;
}
.nav button {
  margin-right: 10px;
  padding: 8px 16px;
}
.nav button.active {
  background: #409eff;
  color: white;
  border: none;
}
.panel {
  margin-top: 20px;
}
.input-tabs {
  margin-bottom: 20px;
}
.input-tabs button {
  margin-right: 10px;
  padding: 6px 12px;
}
.input-tabs button.active {
  background: #67c23a;
  color: white;
  border: none;
}
.single-input, .batch-input {
  margin-bottom: 20px;
}
.stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}
.stat-card {
  width: 200px;
  text-align: center;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-top: 10px;
}
.charts {
  display: flex;
  gap: 20px;
}
.chart-item {
  flex: 1;
}
</style>